package com.kbt.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import com.google.gson.Gson;
import com.kbt.base.BaseApplication;
import com.kbt.commont.Constants;
import com.kbt.global.data.ApplicationData;
import com.kbt.model.data.AddressBean;
import com.kbt.model.data.BaseBean;
import com.kbt.model.data.ShopCarBean;
import com.kbt.model.data.UserAddressInfoModel;
import com.kbt.net.RequestManager;
import com.kbt.ui.CityPopWindow;
import com.kbt.util.data.StaticData;
import com.kbt.util.tool.BtnSetting;
import com.kbt.util.tool.CommonStatus;
import com.kbt.util.tool.UUIDUtilTool;
import com.kbt.util.utils.SharePreferenceUtils;
import com.kbt.util.utils.Utils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Title: KBT_ANDRIOD
 * @Copyright: KJ Co., Ltd. Copyright 2015-2020,  All rights reserved
 * @Description: 新建收获地址视图
 * @author: zhgk
 * @data: 2015/8/14 8:40
 * @version: V1.0
 */

public class AddressAddActivity extends Activity implements RequestManager.ResponseInterface{

    private EditText userNameEdit;
    private EditText userMobileEdit;
    private EditText userIDCardEdit;
    private EditText userAddressMainEdit;
    private EditText userAddressInfoEdit;
    private RequestManager mRequestManager;
    private Map<String, String> map =null;
    private BaseBean baseBean;
    private String userName ;
    private String userMobile ;
    private String userIDCarNo ;
    private String userAddressMain ;
    private String userAddreeInfo;
    private String youZhengNumber;
    private AddressBean addressBean = null;
    private String biaoji ;
    private String biaoji2 ;

    private List<ShopCarBean> goodInfoList;
    private EditText post_code;
    private SharePreferenceUtils share;
    private String order_jf_sub_je;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        this.requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.address_add);
        this.getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title_return_btn);

        //设置返回按钮事件,关闭当前Activity，返回数据
        ImageView returnImg = (ImageView) findViewById(R.id.return_btn);
        returnImg.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                BaseApplication.getInstance().removeActivity(AddressAddActivity.this);
                if (biaoji != null && biaoji.equals("1")) {
                    Intent intent = new Intent(AddressAddActivity.this, GoodForPayActivity.class);
                    intent.putExtra("list", (Serializable) goodInfoList);
                    intent.putExtra("biaoji", biaoji2);
                    if (order_jf_sub_je != null && !"".equals(order_jf_sub_je)) {
                        intent.putExtra("order_jf_sub_je", order_jf_sub_je);
                    }
                    startActivity(intent);
                }
                finish();
            }
        });

        TextView appTitleView = (TextView) findViewById(R.id.center_title);
        appTitleView.setText("维护收货地址");

        BaseApplication.getInstance().addActivity(this);
        mRequestManager = new RequestManager();
        mRequestManager.setResponseListener(this);
        map = new HashMap<String, String>();
        Intent intent =getIntent();
        addressBean = (AddressBean)intent.getSerializableExtra("address");
        biaoji = intent.getStringExtra("tag");
        biaoji2 = intent.getStringExtra("biaoji");
        order_jf_sub_je = intent.getStringExtra("order_jf_sub_je");
        goodInfoList = new ArrayList<ShopCarBean>();
        goodInfoList = (List<ShopCarBean>) getIntent().getSerializableExtra("list");
        share = new SharePreferenceUtils(AddressAddActivity.this);
        //初始化视图
        initLayoutView();
        //设置确定提交按钮
        Button submitBtn = (Button) findViewById(R.id.saveBtn);
        BtnSetting.setBtnBackground(submitBtn, 0, Color.RED, Color.RED, 5);
        submitBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //获取数据
                 userName = userNameEdit.getText().toString().trim();
                 userMobile = userMobileEdit.getText().toString().trim();
                 userIDCarNo = userIDCardEdit.getText().toString().trim();
                 userAddressMain = userAddressMainEdit.getText().toString().trim();
                 userAddreeInfo = userAddressInfoEdit.getText().toString().trim();
                 youZhengNumber = post_code.getText().toString().trim();

                if (userName.length() == 0) {
                    Toast.makeText(AddressAddActivity.this, "请填写收货人姓名！", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (userMobile.length() == 0) {
                    Toast.makeText(AddressAddActivity.this, "请填写手机号码！", Toast.LENGTH_SHORT).show();
                    return;
                }
                if(userMobile.length()<11){
                    Toast.makeText(AddressAddActivity.this, "请填写正确的手机号码！", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (userAddressMain.length() == 0) {
                    Toast.makeText(AddressAddActivity.this, "请填写省市区！", Toast.LENGTH_SHORT).show();
                    return;
                }
//                if(youZhengNumber.length()==0){
//                    Toast.makeText(AddressAddActivity.this, "请填写邮政编码！", Toast.LENGTH_SHORT).show();
//                    return;
//                }
                if (userAddreeInfo.length() == 0) {
                    Toast.makeText(AddressAddActivity.this, "请填写详细地址！", Toast.LENGTH_SHORT).show();
                    return;
                }

                if(addressBean==null){
                    //增加收货地址
                    httpAddress(userName,userMobile,userIDCarNo,userAddressMain,youZhengNumber,userAddreeInfo);
                }else{
                    httpUpdateAddress(userName,userMobile,userIDCarNo,userAddressMain,youZhengNumber,userAddreeInfo);
                }

            }
        });


    }
    //增加收货地址
    public void httpAddress(String userName,String userMobile,String userIDCarNo,String userAddressMain,String youZhengNumber,String userAddreeInfo){
        if(Utils.isNetworkAvailable(AddressAddActivity.this)) {
            map.clear();
            map.put("methodType", "add");
            Gson gson = new Gson();
            Map dataMap = new HashMap<String,String>();
            dataMap.put("user_mobile", userMobile);
            dataMap.put("user_name", userName);
            dataMap.put("user_card_id", userIDCarNo);
            dataMap.put("user_address_ssq", userAddressMain);
            dataMap.put("post_code", youZhengNumber);
            dataMap.put("user_address_info", userAddreeInfo);
            dataMap.put("create_user_mobile", share.getString("user_mobile", ""));
            map.put("data", gson.toJson(dataMap));
            mRequestManager.post(Constants.ServiceInterFace.addAddressURL, map, Constants.RequestTag.addAddressTag, BaseBean.class);
        }else{
            Toast.makeText(AddressAddActivity.this,R.string.Wangluo,Toast.LENGTH_SHORT).show();
        }
    }
    //修改收货地址
    public void httpUpdateAddress(String userName,String userMobile,String userIDCarNo,String userAddressMain,String youZhengNumber,String userAddreeInfo){
        if(Utils.isNetworkAvailable(AddressAddActivity.this)) {
            map.clear();
            map.put("methodType", "update");
            Gson gson = new Gson();
            Map dataMap = new HashMap<String,String>();
            dataMap.put("user_mobile", userMobile);
            dataMap.put("user_name", userName);
            dataMap.put("user_card_id", userIDCarNo);
            dataMap.put("user_address_ssq", userAddressMain);
            dataMap.put("post_code", youZhengNumber);
            dataMap.put("user_address_info", userAddreeInfo);
            dataMap.put("create_user_mobile", share.getString("user_mobile", ""));
            dataMap.put("address_id", addressBean.getAddress_id());
            map.put("data", gson.toJson(dataMap));
            mRequestManager.post(Constants.ServiceInterFace.addAddressURL, map, Constants.RequestTag.addAddressTag, BaseBean.class);
        }else{
            Toast.makeText(AddressAddActivity.this,R.string.Wangluo,Toast.LENGTH_SHORT).show();
        }
    }

    /********
     * 初始化LayoutView视图
     */
    private void initLayoutView() {

        userNameEdit = (EditText) findViewById(R.id.userName);
        userMobileEdit = (EditText) findViewById(R.id.userMobile);
        userMobileEdit.setText(share.getString("user_mobile",""));
        userIDCardEdit = (EditText) findViewById(R.id.userIdentify);
        userAddressMainEdit = (EditText) findViewById(R.id.userAddressMain);
        userAddressInfoEdit = (EditText) findViewById(R.id.userAddressInfo);
        post_code  = (EditText) findViewById(R.id.postOfficeNumber);

        if(addressBean!=null){
            userNameEdit.setText(addressBean.getUser_name()+"");
            userMobileEdit.setText(addressBean.getUser_mobile()+"");
            userAddressMainEdit.setText(addressBean.getUser_address_sxq()+"");
            userAddressInfoEdit.setText(addressBean.getUser_address_info()+"");
            post_code.setText(addressBean.getPost_code() + "");
        }

        userAddressMainEdit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(AddressAddActivity.this.getCurrentFocus().getWindowToken(), 0);
                PopupWindow popupWindow = new CityPopWindow(AddressAddActivity.this, v);
                popupWindow.showAtLocation(findViewById(R.id.userAddressMain),
                        Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0);
            }
        });
    }

    @Override
    public <T> void successResponse(T parsedGSON, int tag) {
        if (tag == Constants.RequestTag.addAddressTag) {
            /** 判断返回值不为空 **/
            if (parsedGSON != null) {
                baseBean = (BaseBean) parsedGSON;
                if(baseBean.getResult().equals("success")){
                    Toast.makeText(AddressAddActivity.this, "" + baseBean.getMsg(), Toast.LENGTH_SHORT).show();
                    BaseApplication.getInstance().removeActivity(AddressAddActivity.this);
                    if(biaoji!=null&&biaoji.equals("1")){
                        Intent intent = new Intent(AddressAddActivity.this, GoodForPayActivity.class);
                        intent.putExtra("list", (Serializable) goodInfoList);
                        intent.putExtra("biaoji", biaoji2);
                        if(order_jf_sub_je!=null&&!"".equals(order_jf_sub_je)){
                            intent.putExtra("order_jf_sub_je",order_jf_sub_je);
                        }
                        startActivity(intent);
                    }
                    finish();
                }else{
                    Toast.makeText(AddressAddActivity.this,""+baseBean.getMsg(),Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    @Override
    public void errorResonse(String retmeg, int tag) {
        Toast.makeText(AddressAddActivity.this,R.string.noWangluo,Toast.LENGTH_SHORT).show();
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if (keyCode == KeyEvent.KEYCODE_BACK )
        {
            BaseApplication.getInstance().removeActivity(AddressAddActivity.this);
            if(biaoji!=null&&biaoji.equals("1")){
                Intent intent = new Intent(AddressAddActivity.this, GoodForPayActivity.class);
                intent.putExtra("list", (Serializable) goodInfoList);
                intent.putExtra("biaoji", biaoji2);
                if(order_jf_sub_je!=null&&!"".equals(order_jf_sub_je)){
                    intent.putExtra("order_jf_sub_je",order_jf_sub_je);
                }
                startActivity(intent);
            }
            finish();
        }

        return false;

    }
    @Override
    public boolean onTouchEvent(android.view.MotionEvent event) {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        return imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
    }

}
